package com.zhan.easyexcelorder.controller;

import com.alibaba.excel.support.ExcelTypeEnum;
import com.zhan.easyexcelorder.listener.ExcelException;
import com.zhan.easyexcelorder.listener.ExcelUtils;
import com.zhan.easyexcelorder.model.SysUserExcelEntity;
import com.zhan.easyexcelorder.service.ExcelUser;
import com.zhan.easyexcelorder.service.SysUserService;
import com.zhan.utils.ApiResponse;
import com.zhan.utils.MyExceptionUtil;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import static com.zhan.utils.ApiResponse.success;


/**
 * @author zhan
 * @since 2019-12-05 19:14
 */

@Api(tags = "ExcelController", description = "Excel 导入，导出 相关接口")
@RestController
public class ExcelController extends AbstractController<SysUserService> {

    private static final Logger logger = LoggerFactory.getLogger(ExcelController.class);

    @Autowired
    private ExcelUser excelUser;

    @RequestMapping("/importExcel")
    public ApiResponse exportExcel(@RequestParam("file") MultipartFile file) {
        try {
            excelUser.importData(file);
        } catch (ExcelException e) {
            e.printStackTrace();
            MyExceptionUtil.throwErrMessage("导入失败");
        }
        return success("导入成功");
    }

    @RequestMapping("/exportExcel")
    public ApiResponse importExcel(HttpServletResponse response) throws IOException {

        List<SysUserExcelEntity> list = new ArrayList<>();
        SysUserExcelEntity model = new SysUserExcelEntity("张三", "15190256344", "1000", "10001", "系统管理员", "洛克希德马丁/武器研发部");
        SysUserExcelEntity model2 = new SysUserExcelEntity("张三2", "15190256345", "1001", "10002", "系统管理员4", "洛克希德马丁/武器研发部3");
        SysUserExcelEntity model3 = new SysUserExcelEntity("张三3", "15190256346", "1002", "10003", "系统管理员5", "洛克希德马丁/武器研发部5");

        list.add(model);
        list.add(model2);
        list.add(model3);
        try {
            ExcelUtils.writeExcel(response, list, "导出测试", "没有设定sheet名称", ExcelTypeEnum.XLSX, SysUserExcelEntity.class);
        } catch (ExcelException e) {
            logger.error("导出失败", e);
        }
        return success("导出成功");
    }
}
